package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.PeachblossomApi;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Voice;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author ZPeng
 */
@DubboService
public class PeachblossomApiImpl implements PeachblossomApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加语音
     * @author LittleLynn
     */
    @Override
    public void add(Voice voice) {
        mongoTemplate.insert(voice);
    }

    /**
     * 查询不同性别用户的语音
     * @param userId
     * @param gender
     * @param voiceDate
     * @return
     */
    @Override
    public Voice findVoiceByGender(Long userId, String gender, Set voiceDate) {
        //定义查询条件，用于根据当前用户id查询喜欢表，查找是否有此发送语音的用户
        Query queryLike = new Query();
        queryLike.addCriteria(Criteria.where("userId").is(userId).and("isLike").is(false));
        queryLike.fields().include("likeUserId");
        //根据当前用户id查询喜欢表，判断用户是否喜欢
        List<UserLike> userLikeList = mongoTemplate.find(queryLike, UserLike.class);//获得所有不喜欢用户
        //遍历获得所有不喜欢用户的ids
        List<Long> userLikeIds = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            userLikeIds.add(userLike.getLikeUserId());
        }

        Query query = new Query();
        //将当前用户id放入排除的不喜欢用户ids集合里
        userLikeIds.add(userId);
        //排除相同性别和不喜欢用户和已读用户的id
        query.addCriteria(Criteria.where("gender").ne(gender)
                .and("userId").nin(userLikeIds)
                .and("created").nin(voiceDate)
        );
        //查询所有符合条件的数据
        int count = (int) mongoTemplate.count(query, Voice.class);
        //随机查询一位
        if (count>1){
            query.skip(RandomUtils.nextInt(1, count));
        }
        //查询一个符合条件的语音
        return mongoTemplate.findOne(query, Voice.class);
    }

}
